const sqsListener = require('./sqsListener');
const dispatcher = require('./dispatcher');
const config = require('../../../config/config.local');

const subscription = {};
subscription.receive = async function () {
  try {
    const notifications = await sqsListener.receive();
    if (notifications != null && notifications.length > 0) {
      // console.log(notification);
      // dispatch notification
      for (const notification of notifications) {
        await dispatcher.dispatch(notification);
        console.log(`ready to delete message, receiptHandle is ${notification.Notification.NotificationMetaData.ReceiptHandle}`);
        await sqsListener.deleteMessage(notification.Notification.NotificationMetaData.ReceiptHandle);
      }
    }
  } catch (err) {
    console.error(err);
  }

  setTimeout(subscription.receive, config.subscription.pollingInterval)
};

module.exports = subscription;